﻿using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.Model;
using ConfigInfoWebPlatform.Model.Model;
using ConfigInfoWebPlatform.Nlog;
using FileSecretAssemblyStandard;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 精细化配置管理模块
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class DelicacyCfgFileController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;
        readonly string initDB;
        readonly InterfaceFileSecret FileSecret;
        /// <summary>
        /// 精细化配置管理模块
        /// </summary>
        /// <param name="logHelper"></param>
        /// <param name="configuration"></param>
        /// <param name="fileSecret"></param>
        public DelicacyCfgFileController(LogHelper logHelper, IConfiguration configuration, InterfaceFileSecret fileSecret)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
            initDB = configuration["AppSetting:initDB"].ToString();
            FileSecret = fileSecret;
        }

        /// <summary>
        /// Index
        /// </summary>
        /// <param name="dir">首页</param>
        /// <param name="page">首页</param>
        /// <param name="limit">首页</param>
        /// <returns></returns>
        // GET: Manager/CaseElementCfgFile
        [HttpGet("index")]
        public JsonResult Index(string dir, int page, int limit)
        {
            var fname = Request.Query["fname"];
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取用户角色操作权限
            DAL_Role dal_Role = new DAL_Role();
            var isOperate = dal_Role.GetOperateAuthorityByRid(user.R_id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = (version?.Catalogue == "dev" || string.IsNullOrWhiteSpace(version?.Catalogue))
                                ? ""
                                : version?.Catalogue;
            string filepath = Path.Combine(configRootPath, versionPath, dir).Replace("\\", "/");
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
            //进行将文件信息同步到数据库中
            this.SyncFileToData(dir,versionPath, "xml");
            // 获取流程配置的文件结构
            DAL_ConfigFile configFile = new DAL_ConfigFile();
            List<ConfigFileInfoModel> caseElementCfgFileInfos = configFile.GetConfigFiles(dir);
            if (!string.IsNullOrWhiteSpace(fname))
                caseElementCfgFileInfos = caseElementCfgFileInfos.Where(x => x.name.Contains(fname)).ToList();
            // 获取页面的数据
            List<ConfigFileInfoModel> CfgFileInfos = new List<ConfigFileInfoModel>();
            if (caseElementCfgFileInfos != null && caseElementCfgFileInfos.Count > 0)
            {
                CfgFileInfos = caseElementCfgFileInfos.Skip((page - 1) * limit).Take(limit).ToList();
            }
            return new JsonResult(new { code = 0, msg = "成功", count = caseElementCfgFileInfos.Count(), isOperate = user.Name == "admin" ? 1 : isOperate, data = CfgFileInfos });
        }

        /// <summary>
        /// 将文件信息同步到数据库中
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="filetype"></param>
        /// <param name="versionPath"></param>
        private void SyncFileToData(string dir,string versionPath, string filetype)
        {
            //获取当前目录的所有文件信息
            var rootPath = string.IsNullOrWhiteSpace(versionPath)
                        ? configRootPath
                        : $"{configRootPath}/{versionPath}";
            DirectoryInfo directory = new DirectoryInfo(Path.Combine(rootPath, dir));
            var files = directory.GetFiles("*." + filetype);
            // 获取流程配置的文件结构
            DAL_ConfigFile configFile = new DAL_ConfigFile();
            var configFileInfos = configFile.GetConfigFiles(dir);
            foreach (var fileInfo in files)
            {
                string filenewrelative = fileInfo.FullName.Replace(@"\", "/").Replace(rootPath.Replace(@"\", "/") + "/", "");
                string filename = fileInfo.Name;
                bool isexit = configFileInfos.Any(row => row.name == filename && row.path == filenewrelative);
                if (!isexit)
                {
                    //插入数据；
                    ConfigFileInfoModel configFileInfo = new ConfigFileInfoModel();
                    configFileInfo.currentId = System.Guid.NewGuid().ToString("N");
                    configFileInfo.name = filename;
                    configFileInfo.ctype = "F";
                    configFileInfo.path = filenewrelative;
                    configFileInfo.parentPath = filenewrelative.Replace("/" + filename, "");
                    configFileInfo.fileSize = fileInfo.Length.ToString() + "B";
                    configFileInfo.updateTime = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                    configFileInfo.createdTime = fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                    configFileInfo.level = 3;
                    configFileInfo.programId = 60;
                    configFileInfo.note = "";

                    string parentId = configFile.GetFileId(configFileInfo.parentPath);
                    configFileInfo.parentId = parentId;
                    configFile.AddConfigFile(configFileInfo);
                }
            }
        }
        /// <summary>
        /// 查看文件内容
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        [HttpGet("detail")]
        public ActionResult Detail(string fileName)
        {
            string fileContent = "";
            try
            {
                string filenametemp = Path.Combine(configRootPath, fileName);
                fileContent = FileSecret.DecryptFileToContent(filenametemp);
                return new JsonResult(fileContent);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        [HttpGet("downloadfile")]
        public ActionResult DownLoadFile(string fileName)
        {
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            Result re = new Result();
            if (!string.IsNullOrEmpty(fileName))
            {
                re.code = "1";
                string filenameTemp = Path.Combine(configRootPath, versionPath, fileName);
                string clientFileName = Path.GetFileName(fileName);
                string fileContent = FileSecret.DecryptFileToContent(filenameTemp);
                byte[] bytes = Encoding.UTF8.GetBytes(fileContent);
                //二进制流数据（如常见的文件下载）
                return File(bytes, "application/octet-stream", clientFileName);
            }
            else
            {
                re.code = "0";
                re.message = "下载失败";
                return BadRequest(re);
            }
        }

    }
}
